import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import { setToken, getToken, canTurnTo, setTitle, localRead } from '@/libs/util'
import config from '@/config'
const { homeName } = config;
import { initRouter } from '@/libs/router-util' // ①新增  引入动态菜单渲染

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'


router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
		if (store.state.app.hasGetRouter && store.state.app.menuList && store.state.app.menuList.length > 0) {
			next();
		 } else {
			if(to.name === homeName){
				initRouter().then((r)=>{
					next();
				});
			}else{
				initRouter().then((r)=>{
					next({
						path: to.path
					});
				});
			}
		}
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

// 解决重复点击导航路由报错
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

export default router
